from flask_sqlalchemy import SQLAlchemy
from datetime import datetime
from flask import Flask
import pymysql
from werkzeug.security import generate_password_hash, check_password_hash

pymysql.install_as_MySQLdb()


class config():
    SQLALCHEMY_DATABASE_URI = 'mysql://root:1163196477@localhost:3306/test'
    SQLALCHEMY_TRACK_MODIFICATIONS = False
    SQLALCHEMY_ECHO = False


app = Flask(__name__)
app.config.from_object(config)
db = SQLAlchemy(app)


class BaseModel(object):
    """模型基类，为每个模型补充创建时间与更新时间"""
    create_time = db.Column(db.DateTime, default=datetime.now,index=True)  # 记录的创建时间



class News(BaseModel, db.Model):
    """新闻"""
    __tablename__ = "toutiao01"

    id = db.Column(db.Integer, primary_key=True,index=True)  # 新闻编号
    title = db.Column(db.String(256), nullable=False,index=True,unique=True)  # 新闻标题
    source = db.Column(db.String(64), nullable=False)  # 新闻来源
    digest = db.Column(db.String(512), nullable=False)  # 新闻摘要
    content = db.Column(db.Text, nullable=False)  # 新闻内容
    clicks = db.Column(db.Integer, default=0)  # 浏览量
    index_image_url = db.Column(db.String(256))  # 新闻列表图片路径
    category_id = db.Column(db.Integer, db.ForeignKey("t_category.id"))


    def to_dict(self):
        resp_dict = {
            "id": self.id,
            "title": self.title,
            "source": self.source,
            "digest": self.digest,
            "create_time": self.create_time.strftime("%Y-%m-%d %H:%M:%S"),
            "content": self.content,
            "clicks": self.clicks,
            "index_image_url": self.index_image_url
        }
        return resp_dict



class Category(BaseModel, db.Model):
    """新闻分类"""
    __tablename__ = "t_category"

    id = db.Column(db.Integer, primary_key=True)  # 分类编号
    name = db.Column(db.String(64), nullable=False)  # 分类名
    news_list = db.relationship('News', backref='category', lazy='dynamic')

    def to_dict(self):
        resp_dict = {
            "id": self.id,
            "name": self.name
        }
        return resp_dict


if __name__ == '__main__':
    db.drop_all()
    db.create_all()
    c1=Category(name='推荐')
    c2=Category(name='热点')
    c3=Category(name='科技')
    c4=Category(name='游戏')
    c5=Category(name='汽车')
    c6=Category(name='财经')
    c7=Category(name='搞笑')
    c8=Category(name='浏览排行')
    db.session.add_all([c1,c2,c3,c4,c5,c6,c7,c8])
    # data=News.query.filter(News.title=='习近平会见香港澳门各界庆祝国家改革开放40周年访问团').first()
    # print(data)
    # db.session.delete(data)
    db.session.commit()



